import express from "express"
import Logger from "./logger.ts"
import {initDatabase, listUsers, listUsersPage, saveUser, deleteUser, User} from './crud.ts';

const logger = new Logger('log/express.log')

const app = express()

app.use(express.static('public'))
app.use(express.json())
app.use(express.urlencoded({extended: true}));

app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    let {ip, method, url} = req
    if (url !== '/favicon.ico') {
        logger.info(`收到来自${ip}的${method}请求 ${url}`)
    }
    next()
})

app.get('/list', (req, res) => {
    res.json(listUsers())
})

app.get('/listPage', (req, res) => {
    let page = Number(req.query.page)
    if (isNaN(page)) {
        res.status(400).send('Invalid page number');
    } else {
        res.json(listUsersPage(page, 5))
    }
})

app.post('/update', (req, res) => {
    let user = req.body as User
    saveUser(user)
    res.redirect('http://localhost:8080')
})

app.post('/delete', (req, res) => {
    let user = req.body as User
    if (user.id) {
        deleteUser(user.id)
    }
    res.redirect('http://localhost:8080')
})


app.listen(8080, () => {
    logger.info('在 http://localhost:8080 上启动Express服务')
    initDatabase()
})




